<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Admin\Models\Member;
use App\Admin\Models\MemberWithdraw;
use App\Services\Common;
use App\Services\Store;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Ixudra\Curl\Facades\Curl;
use DB;

class MemberWithdrawController extends Controller
{
	use HasResourceActions;
	
    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('会员')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('会员')
            ->description('详细')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('会员')
            ->description('编辑')
            ->body($this->form($id)->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('申请提现')
            ->description('创建')
            ->body($this->form());
    }
    
//  public function update(Request $request, $id)
//  {
//
//  }
    
//  /**
//   * Handle update.
//   *
//   * @param int $id
//   *
//   * @return \Symfony\Component\HttpFoundation\Response
//   */
//  public function update($id, $data = null)
//  {	
//  	
//      return $this->returnMsg(1, $id);
//  }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new MemberWithdraw);

		$isManager = Admin::user()->isRole('manager');
		$auCode = Admin::user()->auCode;
		$createUser = Admin::user()->name;
		
		if (!$isManager){
			$grid->model()->where('muCode', '=', $auCode);
		}
		$grid->model()->orderBy('mwId', 'desc');

		$appInfo = MemberWithdraw::where('muCode', $auCode)->where('mwStatus', 0)->first();
		if (empty(!$appInfo)){
			$grid->disableCreateButton();
		}

        $grid->mwId('ID');
        $grid->createUser('姓名');
        $grid->mwMoney('提现金额');
        $grid->mwMemo('备注');
        $grid->mwStatus('状态')->using(['0' => '申请中', '1' => '已发放', '2' => '拒绝']);
        $grid->createTime('申请时间');
        $grid->mwCheckTime('审核时间');
//      $grid->waMoney('账户金额')->display(function($waMoney) {
//		    return "<a href='./myTrade?userCode={$this->muCode}'>{$waMoney}</a>";
//		});

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		});
		
		$grid->actions(function ($actions) use($isManager, $createUser) {
		    $actions->disableDelete();
		    $actions->disableEdit();
		    $actions->disableView();
			// prepend一个操作
    		//$actions->prepend("<a class='btn btn-dropbox' href='".route('cardUseList')."?muCode={$actions->row->muCode}'>服务历史</a>");
    		if ($isManager && $actions->row->mwStatus == 0){
    			$actions->prepend('<button data-id="'.$actions->row->mwId.'" type="button" class="btn btn-success btn-xs btnWithdraw">通过</button>');
    		
    			$grayScript = <<<EOT

	$('.btnWithdraw').unbind('click').click(function() {

	    var id = $(this).data('id');
	
	    swal({
	        title: "确认通过该申请？",
	        type: "warning",
	        showCancelButton: true,
	        confirmButtonColor: "#DD6B55",
	        confirmButtonText: "确认",
	        showLoaderOnConfirm: true,
	        cancelButtonText: "取消",
	        preConfirm: function() {
	            return new Promise(function(resolve) {
	                $.ajax({
	                    method: 'post',
	                    url: '../main/checkWithdraw',
	                    data: {
	                        mwId: id,
	                        operator: "{$createUser}"
	                    },
	                    success: function (data) {
	                    	console.log('success data:')
	                    	console.log(data)
	                        $.pjax.reload('#pjax-container');
	                        resolve(data);
	                        
	                        if (data.code == 1){
	                        	location.reload();
	                        }else{
	                        	toastr.warning(data.msg); 
	                        }
	                    }
	                });
	            });
	        }
	    }).then(function(result) {
	    	
	    });
	});

EOT;
				Admin::script($grayScript);
    		}
		});

//		$grid->tools(function (Grid\Tools $tools){
//
//		    $tools->append('<a class="btn btn-sm btn-danger form-history-bac" style="float: right;margin-right: 20px;" href="'.route('chargeView').'"><i class=""></i>&nbsp;会员充值</a>');
//		});

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();
		    
//		    $filter->column(1/2, function ($filter) {
//				$filter->like('muNickName', '姓名');
//				$formartData = array();
//	            $formartData[0] = '女';
//	            $formartData[1] = '男';
//	            $filter->equal('muSex', '性别')->select($formartData);
//			});
//
//			$filter->column(1/2, function ($filter) {
//				$filter->like('muMobile', '手机号');
//				//$filter->equal('muAccount', '店名');
////				$filter->gt('muAccount', '账户余额');
////				$filter->gt('muPoints', '积分');
////			    $filter->gt('muTotalExpend', '总消费');
//			});

		});

		// 默认展开筛选框
		$grid->expandFilter();
		
		// 禁用行选择checkbox
		$grid->disableRowSelector();
		
		// 禁用导出
		$grid->disableExport();
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
    	$Member = new Member();
        $show = new Show($Member->findOrFail($id));

        $show->muId('ID');
        $show->muCode('用户码');
        $show->muNickName('姓名');
//      $show->muRealName('姓名');
        $show->muSex('性别')->using(['0' => '女', '1' => '男']);;
        $show->muMobile('手机号');
        $show->muMemo('备注');
//      $show->muAccount('账户金额');
        $show->muPoints('积分');
        $show->muTotalExpend('总消费');
        $show->createTime('创建时间');
        $show->updateUser('最后修改人');
        $show->updateTime('最后修改时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($id=false)
    {
        return Admin::Form(MemberWithdraw::class, function (Form $form) use($id) {
			
			$sId = Admin::user()->sId;
			$auCode = Admin::user()->auCode;
			$name = Admin::user()->name;
			
			$Common = new Common();
			$accountMoney = $Common->getWalletMoney($sId, $auCode);

			$form->hidden('mcId')->value($sId);
			$form->hidden('muCode')->value($auCode);
			$form->text('accountMoney', '账户余额')->value($accountMoney)->readOnly();
			$form->number('mwMoney', '提现金额')->default($accountMoney)->rules("required", ['required' => '请填写提现金额']);
			$form->text('mwMemo', '备注');
			$form->hidden('createUser')->value($name);
			
			$form->ignore(['accountMoney']);
			
			//保存前回调
			$form->saving(function (Form $form) use($accountMoney) {
			    if ($accountMoney < $form->mwMoney){
			    	$error = new MessageBag([
						'title'   => '提交失败',
				        'message' => '提现金额不能超过账户金额！'
				    ]);
				
				    return back()->with(compact('error'))->withInput();
			    }
			});
			
            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
			    $tools->disableList();
				
			    // 去掉`删除`按钮
			    $tools->disableDelete();
			
			    // 去掉`查看`按钮
			    $tools->disableView();
			
			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});
			
			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//			
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();
			
			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();
			
			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();
			
			    // 去掉`继续创建`checkbox
			    $footer->disableCreatingCheck();
			
			});
        });
    }
}
